package bancosys.tec.security.impl.web.manager;

import java.security.Principal;
import java.util.HashSet;
import java.util.Set;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;

import bancosys.tec.persist.dao.BeanNotFoundException;
import bancosys.tec.security.authorization.Permission;
import bancosys.tec.security.impl.AbstractSecurityManager;
import bancosys.tec.security.impl.SecurityPrincipal;
import bancosys.tec.security.impl.dao.UserDAO;
import bancosys.tec.security.impl.domain.Credential;
import bancosys.tec.security.impl.domain.User;
import bancosys.tec.security.impl.web.WebSecurityContext;
import bancosys.tec.security.impl.web.WebSecurityManager;

/**
 * Controller do componente. Também implementa {@link WebSecurityManager}.
 * 
 * @author Marco
 */
public class HttpApplicationSecurityManager extends AbstractSecurityManager<WebSecurityContext> implements WebSecurityManager {

    private static final Logger LOG = Logger.getLogger(HttpApplicationSecurityManager.class);

    private UserDAO userDao;

    /**
     * Valida a senha do usuário com a senha informada.
     * 
     * @param username nome do usuário.
     * @param password senha informada pelo usuário.
     * @param user usuário.
     * @return <code>true</code> se a senha for válida, <code>false</code> caso contrário.
     */
    private boolean validatePassword(String username, String password, User user) {
        String md5Password = encodePassword(password);
        return user.getPassword().equalsIgnoreCase(md5Password);
    }

    /**
     * Cria o hash da senha
     * 
     * @param password senha
     * @return hash da senha
     */
    public static String encodePassword(String password) {
        return DigestUtils.md5Hex(password);
    }

    /**
     * {@inheritDoc}
     */
    public Subject loadSubject(WebSecurityContext context) {
        return loadSubjectFromWebSecurityContext(context);
    }

    /**
     * Actually loads the subject from the given {@link WebSecurityContext}. Also loads the public and private credentials if necessary
     * 
     * @param context {@link WebSecurityContext}
     * @return {@link Subject}
     */
    @SuppressWarnings("unchecked")
    public static Subject loadSubjectFromWebSecurityContext(WebSecurityContext context) {
        HttpSession session = context.getRequest().getSession();
        Subject subject = (Subject) session.getAttribute(SESSION_KEY);
        if (subject != null && subject.getPrivateCredentials().isEmpty() && subject.getPublicCredentials().isEmpty()) {
            Set<Credential> publicCredentials = (Set<Credential>) context.getRequest().getSession().getAttribute(PUBLIC_CREDENTIALS_KEY);
            Set<Credential> privateCredentials = (Set<Credential>) context.getRequest().getSession().getAttribute(PRIVATE_CREDENTIALS_KEY);
            Subject newSubject = new Subject(true, new HashSet<Principal>(subject.getPrincipals()), publicCredentials, privateCredentials);
            storeSubjectIntoWebSecurityContext(context, newSubject);
            return newSubject;
        }
        return subject;
    }

    /**
     * {@inheritDoc}
     */
    public void storeSubject(WebSecurityContext context, Subject subject) {
        storeSubjectIntoWebSecurityContext(context, subject);
    }

    /**
     * Actually stores the subject from the given {@link WebSecurityContext}. Also stores the public and private credentials if necessary
     * 
     * @param context {@link WebSecurityContext}
     * @param subject the {@link Subject}
     */
    public static void storeSubjectIntoWebSecurityContext(WebSecurityContext context, Subject subject) {
        HttpSession session = context.getRequest().getSession();
        session.setAttribute(SESSION_KEY, subject);
        if (subject != null) {
            session.setAttribute(PUBLIC_CREDENTIALS_KEY, new HashSet<Object>(subject.getPublicCredentials()));
            session.setAttribute(PRIVATE_CREDENTIALS_KEY, new HashSet<Object>(subject.getPrivateCredentials()));
        }
    }

    /**
     * Remove o subject da sessão http.
     * 
     * @param request sessão http.
     */
    public void removeSubject(HttpServletRequest request) {
        HttpSession session = request.getSession();
        removeSubjectFromSession(session);
    }

    /**
     * Removes the subject from the session with its credentials
     * 
     * @param session {@link HttpSession}
     */
    public static void removeSubjectFromSession(HttpSession session) {
        session.removeAttribute(SESSION_KEY);
        session.removeAttribute(PUBLIC_CREDENTIALS_KEY);
        session.removeAttribute(PRIVATE_CREDENTIALS_KEY);
    }

    /**
     * Cria o subject
     * 
     * @param user usuário.
     * @return subject com credenciais/permissoes
     */
    protected Subject createSubject(User user) {
        Set<? extends Permission> pubCredentials = this.getPubCredentials(user);
        Set<? extends Permission> privCredentials = new HashSet<Permission>();
        Set<Principal> principals = new HashSet<Principal>();
        principals.add(new SecurityPrincipal(user.getUsername()));

        return new Subject(true, principals, pubCredentials, privCredentials);
    }

    /**
     * Converte as credenciais do user em permissoes no subject.
     * 
     * @param user user
     * @return set de permissoes.
     */
    @Override
    protected Set<? extends Permission> getPubCredentials(User user) {
        Set<Permission> pubCredentials = new HashSet<Permission>();
        for (Credential credential : user.getAllCredentials()) {
            if (!this.getSecurityService().isSecurityClientActive(credential.getClient().getId())) {
                continue;
            }
            pubCredentials.add(credential.createPermission());
        }

        return pubCredentials;
    }

    /**
     * Devolve o user dao.
     * 
     * @return user dao.
     */
    protected UserDAO getUserDao() {
        if (this.userDao == null) {
            this.userDao = this.getTransactionalController().getDAOFactory().getDAOByClass(UserDAO.class);
        }
        return this.userDao;
    }

    /**
     * {@inheritDoc}
     */
    public Subject login(String username, String password, WebSecurityContext context) {
        this.getTransactionalController().startTransaction();
        boolean success = false;
        Subject subject = null;
        try {
            User user = this.getUserDao().findUser(username);
            if (this.validatePassword(username, password, user)) {
                subject = this.createSubject(user);
                // this.storeSubject(request, subject);
            } else {
                LOG.debug("Senha inválida para o usuário " + username);
            }
            success = true;
        } catch (BeanNotFoundException e) {
            LOG.debug("Usuário " + username + " não encontrado.", e);
        } finally {
            if (success) {
                this.getTransactionalController().commit();
            } else {
                this.getTransactionalController().rollback();
            }
        }
        return subject;
    }

    /**
     * {@inheritDoc}
     * 
     * @see bancosys.tec.security.SecurityManager#logout(javax.servlet.http.HttpServletRequest)
     */
    public void logout(WebSecurityContext context) {
        this.removeSubject(context.getRequest());
    }
}
